package cn.tedu.springboot.security.sety;

import cn.tedu.springboot.security.mapper.AdminMapper;
import cn.tedu.springboot.security.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author BJ
 * @date 2022/10/22 16:23
 * 取消security的登录,使用自己的登录页面
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    AdminMapper adminMapper;

    // Spring security 自动调用 loadUserByUsername()方法
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring security 自动调用 loadUserByUsername()方法");
        AdminLoginInfoVO loginInfo = adminMapper.getLoginInfoByUsername(s);
        if (loginInfo == null) {
            log.debug("用户名[{}]不存在,即将抛出异常!",s);
            String message="登陆失败!用户名或密码错误!";
            throw new BadCredentialsException(message);
        }

        //将权限封装在认证信息中
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : loginInfo.getPermissions()) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        //将数据库中查到的真实数据封装到AdminDetails中返回
        AdminDetails adminDetails = new AdminDetails(loginInfo.getUsername(), loginInfo.getPassword(),
                loginInfo.getEnable() == 1, authorities);
        adminDetails.setId(loginInfo.getId());
        return adminDetails;
    }
}
